﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;

namespace CommonRepositoryInterface.Linq2Sql
{
    public class Linq2SqlRepositoryProvider<T> : IRepositoryProvider, IDisposable
        where T : DataContext, new()
    {
        public DataContext Context { get; private set; }
        private DebugTextWriter debug = new DebugTextWriter();
        public Linq2SqlRepositoryProvider()
            : this(new T())
        { }
        public Linq2SqlRepositoryProvider(DataContext context)
        {
            this.Context = context;
            this.Context.Log = debug;
        }
        public IRepository<T2> CreateRepository<T2>()
            where T2 : class, IDataRecord
        {
            return new Linq2SqlRepository<T2>(this, this.Context);
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (this.Context != null)
            {
                this.Context.Dispose();
                this.Context = null;
            }
        }

        #endregion

        #region IRepositoryProvider Members


        public void SubmitChanges()
        {
            var deletes = (from d in this.Context.GetChangeSet().Deletes
                          where d is ICascadeDelete
                          select (ICascadeDelete)d).ToArray();

            var updates = (from d in this.Context.GetChangeSet().Updates
                          where d is ICascadeUpdate
                          select (ICascadeUpdate)d).ToArray();

            foreach (var item in deletes)
                item.BeforeDelete(this);
            foreach (var item in updates)
                item.BeforeUpdate(this);
            
            this.Context.SubmitChanges();

            foreach (var item in deletes)
                item.AfterDelete(this);
            foreach (var item in updates)
                item.AfterUpdate(this);
        }

        #endregion
    }
}
